using System;
using System.Collections.Generic;
using GameFramework.Business;
using GameFramework.Extensions;
using GameFramework.Update;

namespace GameFramework.Gameplay
{
    /// <summary>
    /// 玩法视图控制器容器实现
    /// </summary>
    internal sealed class GameplayViewControllerContainer : IGameplayViewControllerContainer
    {
        private readonly List<IViewController> m_Controllers = new List<IViewController>();
        private readonly List<IUpdate> m_Updates = new List<IUpdate>();

        public void Initialize()
        {
            var container = CatLib.App.That;
            
            foreach (var controller in m_Controllers)
            {
                try
                {
                    container.Inject(controller);
                    controller.Initialize();
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                }
            }
        }

        public void Dispose()
        {
            foreach (var controller in m_Controllers)
            {
                try
                {
                    controller.Dispose();
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                }
            }
            
            m_Controllers.Clear();
            m_Updates.Clear();
        }

        public void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
            foreach (var update in m_Updates)
            {
                try
                {
                    update.OnUpdate(elapseSeconds, realElapseSeconds);
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                }
            }
        }

        public void Add<T>() where T : class, IViewController
        {
            var controller = Activator.CreateInstance<T>();
            m_Controllers.Add(controller);
            
            if (controller is IUpdate update)
                m_Updates.Add(update);
        }
    }
}